<template>
  <div class="chat-app" :class="theme">
    <div class="chat-container">
      <!-- 侧边栏 -->
      <div class="sidebar">
        <div class="sidebar-header">
          <h2>聊天室</h2>
          <button class="theme-toggle" @click="toggleTheme">
            <span v-if="theme === 'light'">🌙</span>
            <span v-else>☀️</span>
          </button>
        </div>

        <div class="search-box">
          <input type="text" placeholder="搜索聊天..." v-model="searchQuery">
        </div>

        <div class="chat-list">
          <div v-for="chat in filteredChats" :key="chat.id" class="chat-item"
            :class="{ active: activeChat === chat.id }" @click="selectChat(chat.id)">
            <div class="avatar">
              <img :src="chat.avatar" :alt="chat.name">
            </div>
            <div class="chat-info">
              <div class="name-time">
                <span class="name">{{ chat.name }}</span>
                <span class="time">{{ chat.lastMessage.time }}</span>
              </div>
              <div class="last-message">
                <p>{{ chat.lastMessage.text }}</p>
                <span class="unread" v-if="chat.unreadCount > 0">{{ chat.unreadCount }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 主聊天区 -->
      <div class="main-chat">
        <div class="chat-header">
          <div class="header-left">
            <div class="avatar">
              <img :src="currentChat?.avatar" :alt="currentChat?.name" v-if="currentChat">
            </div>
            <div class="chat-title" v-if="currentChat">
              <h3>{{ currentChat.name }}</h3>
              <p>{{ currentChat.status }}</p>
            </div>
          </div>
          <div class="header-right">
            <button class="icon-button">
              <svg viewBox="0 0 24 24" width="20" height="20">
                <path fill="currentColor"
                  d="M12,16A2,2 0 0,1 14,18A2,2 0 0,1 12,20A2,2 0 0,1 10,18A2,2 0 0,1 12,16M12,10A2,2 0 0,1 14,12A2,2 0 0,1 12,14A2,2 0 0,1 10,12A2,2 0 0,1 12,10M12,4A2,2 0 0,1 14,6A2,2 0 0,1 12,8A2,2 0 0,1 10,6A2,2 0 0,1 12,4Z" />
              </svg>
            </button>
          </div>
        </div>

        <div class="messages-container" ref="messagesContainer">
          <div v-for="(message, index) in currentMessages" :key="index" class="message"
            :class="{ 'sent': message.sent, 'received': !message.sent }">
            <div class="message-content">
              <p>{{ message.text }}</p>
              <span class="time">{{ message.time }}</span>
            </div>
          </div>
        </div>

        <div class="message-input">
          <div class="input-tools">
            <button class="icon-button">
              <svg viewBox="0 0 24 24" width="24" height="24">
                <path fill="currentColor" d="M19,13H13V19H11V13H5V11H11V5H13V11H19V13Z" />
              </svg>
            </button>
            <button class="icon-button">
              <svg viewBox="0 0 24 24" width="24" height="24">
                <path fill="currentColor"
                  d="M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2M7,9.5C7,8.7 7.7,8 8.5,8C9.3,8 10,8.7 10,9.5C10,10.3 9.3,11 8.5,11C7.7,11 7,10.3 7,9.5M12,17.23C10.25,17.23 8.71,16.5 7.81,15.42L9.23,14C9.68,14.72 10.75,15.23 12,15.23C13.25,15.23 14.32,14.72 14.77,14L16.19,15.42C15.29,16.5 13.75,17.23 12,17.23M15.5,11C14.7,11 14,10.3 14,9.5C14,8.7 14.7,8 15.5,8C16.3,8 17,8.7 17,9.5C17,10.3 16.3,11 15.5,11Z" />
              </svg>
            </button>
          </div>
          <input type="text" placeholder="输入消息..." v-model="newMessage" @keyup.enter="sendMessage">
          <button class="send-button" @click="sendMessage">
            <svg viewBox="0 0 24 24" width="20" height="20">
              <path fill="currentColor" d="M2,21L23,12L2,3V10L17,12L2,14V21Z" />
            </svg>
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, inject } from 'vue';

// 主题功能
const theme = inject("theme", ref('light'));
const toggleTheme = () => {
  theme.value = theme.value === 'light' ? 'dark' : 'light';
};

// 聊天数据
const searchQuery = ref('');
const activeChat = ref(1);
const newMessage = ref('');

// 模拟聊天列表数据
const chats = ref([
  {
    id: 1,
    name: '张三',
    avatar: 'https://randomuser.me/api/portraits/men/1.jpg',
    status: '在线',
    lastMessage: {
      text: '你好，最近怎么样？',
      time: '10:30'
    },
    unreadCount: 2
  },
  {
    id: 2,
    name: '李四',
    avatar: 'https://randomuser.me/api/portraits/women/2.jpg',
    status: '离线',
    lastMessage: {
      text: '项目进展如何？',
      time: '昨天'
    },
    unreadCount: 0
  },
  {
    id: 3,
    name: '王五',
    avatar: 'https://randomuser.me/api/portraits/men/3.jpg',
    status: '在线',
    lastMessage: {
      text: '晚上一起吃饭吗？',
      time: '周一'
    },
    unreadCount: 5
  },
  {
    id: 4,
    name: '赵六',
    avatar: 'https://randomuser.me/api/portraits/women/4.jpg',
    status: '离线',
    lastMessage: {
      text: '文件已经发给你了',
      time: '上周'
    },
    unreadCount: 0
  }
]);

// 模拟消息数据
const messages = ref({
  1: [
    { text: '你好！', time: '10:00', sent: false },
    { text: '嗨，最近怎么样？', time: '10:05', sent: true },
    { text: '我很好，谢谢！你呢？', time: '10:10', sent: false },
    { text: '也不错，工作有点忙', time: '10:15', sent: true },
    { text: '周末有空一起吃饭吗？', time: '10:20', sent: true },
    { text: '好啊，我很乐意', time: '10:25', sent: false },
    { text: '你好，最近怎么样？', time: '10:30', sent: false }
  ],
  2: [
    { text: '项目进展如何？', time: '昨天 15:30', sent: false }
  ],
  3: [
    { text: '晚上一起吃饭吗？', time: '周一 18:00', sent: false }
  ],
  4: [
    { text: '文件已经发给你了', time: '上周五 14:00', sent: false }
  ]
});

// 计算属性
const filteredChats = computed(() => {
  if (!searchQuery.value) return chats.value;
  return chats.value.filter(chat =>
    chat.name.toLowerCase().includes(searchQuery.value.toLowerCase())
  );
});

const currentChat = computed(() => {
  return chats.value.find(chat => chat.id === activeChat.value);
});

const currentMessages = computed(() => {
  return messages.value[activeChat.value] || [];
});

// 方法
const selectChat = (chatId) => {
  activeChat.value = chatId;
  // 清除未读消息
  const chat = chats.value.find(c => c.id === chatId);
  if (chat) chat.unreadCount = 0;
};

const sendMessage = () => {
  if (!newMessage.value.trim()) return;

  const now = new Date();
  const timeString = `${now.getHours()}:${now.getMinutes().toString().padStart(2, '0')}`;

  messages.value[activeChat.value].push({
    text: newMessage.value,
    time: timeString,
    sent: true
  });

  // 更新最后一条消息
  const chat = chats.value.find(c => c.id === activeChat.value);
  if (chat) {
    chat.lastMessage = {
      text: newMessage.value,
      time: '刚刚'
    };
  }

  newMessage.value = '';

  // 滚动到底部
  nextTick(() => {
    scrollToBottom();
  });
};

const scrollToBottom = () => {
  const container = messagesContainer.value;
  if (container) {
    container.scrollTop = container.scrollHeight;
  }
};

// 引用和生命周期
const messagesContainer = ref(null);

onMounted(() => {
  scrollToBottom();
});

watch(currentMessages, () => {
  scrollToBottom();
}, { deep: true });
</script>

<style scoped>
.chat-app {
  --bg-color: #f8f9fa;
  --text-color: #333;
  --primary-color: #4361ee;
  --secondary-color: #6c757d;
  --border-color: #e1e4e8;
  --card-bg: #fff;
  --hover-bg: #f1f3f5;
  --shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  --message-sent-bg: #4361ee;
  --message-sent-text: #fff;
  --message-received-bg: #f1f3f5;
  --message-received-text: #333;
  --unread-bg: #4361ee;
  --unread-text: #fff;
  --input-bg: #fff;
  --input-border: #e1e4e8;
  --sidebar-bg: #fff;
  --active-chat-bg: #f1f3f5;
}

.chat-app.dark {
  --bg-color: #1a1a1a;
  --text-color: #e0e0e0;
  --primary-color: #4895ef;
  --secondary-color: #8e8e8e;
  --border-color: #333;
  --card-bg: #2d2d2d;
  --hover-bg: #383838;
  --shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
  --message-sent-bg: #4895ef;
  --message-sent-text: #fff;
  --message-received-bg: #383838;
  --message-received-text: #e0e0e0;
  --unread-bg: #4895ef;
  --unread-text: #fff;
  --input-bg: #2d2d2d;
  --input-border: #333;
  --sidebar-bg: #2d2d2d;
  --active-chat-bg: #383838;
}

.chat-app {
  background-color: var(--bg-color);
  color: var(--text-color);
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  transition: background-color 0.3s, color 0.3s;
}

.chat-container {
  display: flex;
  width: 90%;
  max-width: 1200px;
  height: 90vh;
  background-color: var(--card-bg);
  border-radius: 12px;
  overflow: hidden;
  box-shadow: var(--shadow);
}

.sidebar {
  width: 300px;
  border-right: 1px solid var(--border-color);
  background-color: var(--sidebar-bg);
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  padding: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid var(--border-color);
}

.sidebar-header h2 {
  margin: 0;
  font-size: 1.2rem;
  color: var(--text-color);
}

.theme-toggle {
  background: none;
  border: none;
  font-size: 1.2rem;
  cursor: pointer;
  color: var(--text-color);
}

.search-box {
  padding: 12px;
  border-bottom: 1px solid var(--border-color);
}

.search-box input {
  width: 100%;
  padding: 8px 12px;
  border-radius: 20px;
  border: 1px solid var(--border-color);
  background-color: var(--input-bg);
  color: var(--text-color);
  outline: none;
}

.chat-list {
  flex: 1;
  overflow-y: auto;
}

.chat-item {
  display: flex;
  padding: 12px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.chat-item:hover {
  background-color: var(--hover-bg);
}

.chat-item.active {
  background-color: var(--active-chat-bg);
}

.avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 12px;
}

.avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.chat-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  overflow: hidden;
}

.name-time {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
}

.name {
  font-weight: 600;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.time {
  font-size: 0.8rem;
  color: var(--secondary-color);
}

.last-message {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.last-message p {
  margin: 0;
  font-size: 0.9rem;
  color: var(--secondary-color);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  flex: 1;
}

.unread {
  background-color: var(--unread-bg);
  color: var(--unread-text);
  border-radius: 50%;
  width: 20px;
  height: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 0.7rem;
  margin-left: 8px;
}

.main-chat {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.chat-header {
  padding: 16px;
  border-bottom: 1px solid var(--border-color);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
}

.chat-title h3 {
  margin: 0;
  font-size: 1.1rem;
}

.chat-title p {
  margin: 0;
  font-size: 0.8rem;
  color: var(--secondary-color);
}

.icon-button {
  background: none;
  border: none;
  cursor: pointer;
  color: var(--secondary-color);
  padding: 4px;
  border-radius: 4px;
}

.icon-button:hover {
  background-color: var(--hover-bg);
}

.messages-container {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
}

.message {
  max-width: 70%;
  margin-bottom: 16px;
  display: flex;
}

.message.sent {
  align-self: flex-end;
}

.message.received {
  align-self: flex-start;
}

.message-content {
  padding: 10px 14px;
  border-radius: 18px;
  position: relative;
}

.message.sent .message-content {
  background-color: var(--message-sent-bg);
  color: var(--message-sent-text);
  border-bottom-right-radius: 4px;
}

.message.received .message-content {
  background-color: var(--message-received-bg);
  color: var(--message-received-text);
  border-bottom-left-radius: 4px;
}

.message-content p {
  margin: 0;
}

.message-content .time {
  font-size: 0.7rem;
  margin-top: 4px;
  display: block;
  text-align: right;
  opacity: 0.8;
}

.message-input {
  padding: 12px;
  border-top: 1px solid var(--border-color);
  display: flex;
  align-items: center;
  background-color: var(--card-bg);
}

.input-tools {
  display: flex;
  margin-right: 8px;
}

.input-tools .icon-button {
  margin-right: 4px;
}

.message-input input {
  flex: 1;
  padding: 10px 16px;
  border-radius: 20px;
  border: 1px solid var(--border-color);
  background-color: var(--input-bg);
  color: var(--text-color);
  outline: none;
}

.send-button {
  background-color: var(--primary-color);
  color: white;
  border: none;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-left: 8px;
  cursor: pointer;
}

.send-button:hover {
  opacity: 0.9;
}
</style>